package com.educate.book.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.common.web.IdGen;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.educate.book.dao.BookCatalogueDao;
import com.educate.book.model.bo.BookCatalogueBO;
import com.educate.book.model.po.BookCatalogue;
import com.educate.book.rpc.api.BookCatalogueService;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class BookCatalogueServiceImpl implements BookCatalogueService {

    @Resource BookCatalogueDao bookCatalogueDao;

    @Override
    public String create(BookCatalogueBO bo) {
    	bo.setBookCatalogueId(IdGen.uuid());
        bookCatalogueDao.insert(bo);
        return bo.getBookCatalogueId();
    }

    @Override
    public void delete(BookCatalogueBO bo) {
        bookCatalogueDao.delete(bo);
    }

    @Override
    public void delete(String bookCatalogueId) {
        bookCatalogueDao.deleteById(bookCatalogueId);
    }

    @Override
    public BookCatalogueBO detail(String bookCatalogueId) {
        Optional<BookCatalogue> optional = bookCatalogueDao.findById(bookCatalogueId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new BookCatalogueBO(optional.get());
    }

    @Override
    public BookCatalogueBO detail(BookCatalogueBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(BookCatalogueBO bo) {
        Optional<BookCatalogue> optional = bookCatalogueDao.findById(bo.getBookCatalogueId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        bookCatalogueDao.save(optional.get());
    }

    @Override
    public Page<BookCatalogueBO> query(BookCatalogueBO bo, PageRequest pageRequest) {
        return bookCatalogueDao.query(bo, pageRequest).map(BookCatalogueBO::new);
    }

    @Override
    public List<BookCatalogueBO> list(BookCatalogueBO bo) {
        List<BookCatalogue> result = bookCatalogueDao.findAll();
        return ListUtils.map(result, BookCatalogueBO::new);
    }
}
